<template>
  <div class="container">
    <el-card class="entering-container">
      <div slot="header">
        <span>{{ title }}</span>
      </div>
      <el-form
        :model="dataForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="dataForm.subjectID" placeholder="请选择" @change="getSubjectChange">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="dataForm.catalogID" placeholder="请选择">
            <el-option
              v-for="item in directorys"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业：" rop="enterpriseID">
          <el-select v-model="dataForm.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in companys"
              :key="item.id"
              :label="item.shortName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市：" prop="province">
          <!-- 省 -->
          <el-select
            class="city"
            v-model="dataForm.province"
            @change="handleProvince"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in citySelect.province"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <!-- 市 -->
          <el-select class="city" v-model="dataForm.city" placeholder="请选择">
            <el-option
              v-for="(item, index) in citySelect.cityDate"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="dataForm.direction" placeholder="请选择">
            <el-option v-for="(item, index) in direction" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="dataForm.questionType">
            <el-radio
              v-for="(item, index) in questionType"
              :key="index"
              :label="item.value.toString()"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="dataForm.difficulty">
            <el-radio
              v-for="(item, index) in difficulty"
              :key="index"
              :label="item.value.toString()"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item class="editor" label="题干：" prop="question">
          <quill-editor v-model="dataForm.question" :options="editorOptions"></quill-editor>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项：" v-model="options" v-if="dataForm.questionType !== '3'">
          <div class="option_item" v-for="item in dataForm.options" :key="item.id">
            <!-- 单选 -->
            <el-radio v-if="dataForm.questionType === '1'" v-model="item.isRight">{{ item.code }}：</el-radio>
            <!-- 多选 -->
            <el-checkbox
              v-if="dataForm.questionType === '2'"
              v-model="item.isRight"
            >{{ item.code }}：</el-checkbox>
            <!-- 输入框 -->
            <el-input v-model.trim="item.title"></el-input>
            <!-- 上传图片 -->
            <el-upload class="avatar-uploader" action="photolist">
              <span>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <el-tag type="danger">+增加选项与答案</el-tag>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频">
          <el-input class="el-select" v-model="dataForm.videoURL"></el-input>
        </el-form-item>
        <!-- 答案解析富文本 -->
        <el-form-item class="editor" label="答案解析：" prop="answer">
          <quill-editor v-model="dataForm.answer" :options="editorOptions"></quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注">
          <el-input rows="4" class="textarea" type="textarea" v-model="dataForm.remarks"></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签：">
          <el-select placeholder="请选择试题标签" v-model="dataForm.tags">
            <el-option
              v-for="item in tags"
              :key="item.value"
              :value="item.value.toString()"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item><el-button
            v-if="this.$route.query.id"
            type="success"
            @click="submit()"
            :loading="isLoading"
          >
            确认修改
          </el-button>
          <el-button v-else type="primary" @click="submit()" :loading="isloading"
            >确认提交</el-button
          >
          
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入科目数据请求
import { list as subjects } from '@/api/hmmm/subjects.js'
// 导入目录数据请求
import { list as catalog } from '@/api/hmmm/directorys.js'
// 导入企业数据请求
import { list as enterprise } from '@/api/hmmm/companys.js'
//导入城市数据
import { provinces, citys } from '@/api/hmmm/citys.js'
//导入 方向、题型、难度
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 导入标签
import { simple } from '@/api/hmmm/tags.js'
// 导入添加接口、试题详情
import { add, detail } from '@/api/hmmm/questions.js'

export default {
  data() {
    return {
      //定义城市选择
      citySelect: {
        province: [],
        cityDate: []
      },
      // 科目列表
      subjectList: [],
      // 目录列表(二级目录)
      directorys: [],
      //企业列表
      companys: [],
      // 方向
      direction,
      //题型
      questionType,
      // 难度
      difficulty,
      // 图片列表
      photolist: [],
      //选项数量
      options: 4,
      //标签
      tags: '',
      //初始化loading状态
      isloading: false,
      // 定义标题
      title: '',
      // 表单数据
      dataForm: {
        subjectID: null,
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [],
        videoURL: '',
        answer: '',
        videoURL: '',
        remarks: '',
        tags: '',
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '前选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '前选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入解析', trigger: 'blur' }
        ]
      },
      // 富文本配置对象
      editorOptions: {
        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],//粗体，斜体，下划线，删除线
              ['blockquote', 'code-block']//引号，引用
              // [{ 'header': 1 }, { 'header': 2 }],
              // [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              // [{ 'script': 'sub' }, { 'script': 'super' }],
              // [{ 'indent': '-1' }, { 'indent': '+1' }],
              // [{ 'direction': 'rtl' }],
              // [{ 'size': ['small', false, 'large', 'huge'] }],
              // [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              // [{ 'font': [] }],
              // [{ 'color': [] }, { 'background': [] }],
              // [{ 'align': [] }],
              // ['clean'],
              // ['link', 'image', 'video']
            ],
            // history: {
            //   delay: 1000,
            //   maxStack: 50,
            //   userOnly: false
            // },
            // imageDrop: true,
            // 图片大小的配置
            // imageResize: {
            //   displayStyles: {
            //     backgroundColor: 'black',
            //     border: 'none',
            //     color: 'white'
            //   },
            //   modules: ['Resize', 'DisplaySize', 'Toolbar']
            // }
          }
        },
        placeholder: '' //占位符
      }

    }
  },
  // 钩子函数页面加载时渲染
  created() {
    // 获取学科
    this.getSubjectList()
    //获取目录列表
    // this.getDirectory()
    // 添加选项数据
    this.addOptions(this.options)
    //获取企业
    this.getenterpriselist()
    //获取城市
    this.getCityData()
    // 渲染标签
    // this.getTags()
    // 提交数据表单
    // this.addFrom()
    // 判断是新增还是修改数据
    this.isChange()
  },

  methods: {
    // 学科
    async getSubjectList() {
      const { data: res } = await subjects()
      this.subjectList = res.items
      // console.log(res.items, 'subjectList')
      // console.log(this.subjectID)
    },
    //目录
    async getDirectory() {
      const { data: res } = await catalog({ subjectID: this.dataForm.subjectID })
      this.directorys = ''
      this.directorys = res.items
      // console.log(res,'目录')

    },
    // 学科一级下拉列表触发的change事件
    getSubjectChange() {
      this.getDirectory() // 学科改变渲染目录
      this.getTags() // 触发获取标签列表
    },
    //企业
    async getenterpriselist() {
      const { data: res } = await enterprise()
      this.companys = res.items
      // console.log(this.companys)
    },
    //城市
    //获取省份
    getCityData: function () {
      this.citySelect.province = provinces()
    },
    //获取到市
    handleProvince: function (e) {
      this.citySelect.cityDate = citys(e)
      // console.log(e)
      this.dataForm.city = ''
    },
    //获取标签
    async getTags() {
      const res = await simple({ subjectID: this.dataForm.subjectID })
      // 根据学科的不同请求不同的数据
      this.tags = res.data
      // console.log(res.data, 'hello')
    },
    //添加选项数据
    addOptions(num) {
      for (let i = 0; i < num; i++) {
        this.$set(this.dataForm.options, i, {
          id: i, // 选项id
          code: String.fromCharCode(65 + i), // 选项代码(A的编码是65, B, C, D……)
          title: '', // 选项标题
          img: '', // 选项图片地址
          isRight: false // 选项答案是否正确(初始值都为false【未被选中】)
        })
      }
    },
    // 判断是修改还是新增
    isChange() {
      if (this.$route.query.id) {
        this.title = '试题修改'
        this.getDetail()
        console.log('试题修改')
      } else {
        console.log('试题录入')
        this.title = '试题录入'
      }
    },
    // 若为修改请求新增数据
    async getDetail() {
      try {
        const data = {}
        data.id = this.$route.query.id
        const res = await detail(data)
        res.data.options.forEach((item) => {
          item.isRight = !item.isRight
        })
        this.dataForm = res.data
        // 触发学科联动
        this.getSubjectChange()
      } catch (err) {
        console.log(err)
        this.$message.error('无法获取试题信息')
      }
    },
    // 提交表单
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.addFrom()
        } else {
          this.$message.error('请按要求填写表单！')
          return false
        }
      })
    },
    async addFrom() {
      try {
        this.isloading = true // 开启加载动画
        const { data: res } = await add(this.dataForm)
        this.$message.success('添加数据成功')
        this.$router.push('/questions/list')
        console.log(res)
      } catch (err) {
        console.log(err, '错误')
        this.$message.error('添加数据失败')
      }
      this.isloading = false //关闭加载动画
    }


  }
}
</script>

<style scoped lang='less'>
.entering-container {
  margin: 20px;
  .el-select {
    width: 400px;
    height: 36px;
    .el-input {
      width: 100%;
    }
  }
  .city {
    width: 198px !important;
    &:last-child {
      margin-left: 4px;
    }
  }
  .editor {
    height: 240px;
    .quill-editor {
      height: 186px;
    }
  }
  .option_item {
    margin-bottom: 20px;
    .el-radio {
      margin-right: 0;
    }
    .el-input {
      width: 240px;
    }
    .avatar-uploader {
      margin-left: 5px;
      position: relative;
      width: 100px;
      height: 60px;
      border: 1px dashed #ccc;
      border-radius: 10px;
      display: inline-block;
      vertical-align: middle;
      line-height: 60px;
      font-size: 14px;
      text-align: center;
      .el-icon-circle-close {
        position: absolute;
        top: -5px;
        right: -5px;
        background: #fff;
      }
    }
  }
  .textarea {
    width: 400px;
  }
}
</style>
